package com.jjclub.controller;

import com.alibaba.fastjson.JSONArray;
import com.jjclub.entity.JjclubMenu;
import com.jjclub.entity.JjclubUser;
import com.jjclub.esDao.MarryDao;
import com.jjclub.service.JjclubUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import java.util.List;


/**
 * @Classname LoginController
 * @Description TODO
 * @Date 2019/11/6 10:33
 * @Created by jq
 */
@Controller

public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private JjclubUserService jjclubUserService;

    @Autowired
    private MarryDao marryDao;

    @ApiOperation(value = "登录" ,  notes="平台登录接口")
    @PostMapping("/loginAction")
    public String login(JjclubUser user, Model model){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginid(), user.getPassword().toCharArray());
        try {
            subject.login(token);    //身份认证
            return "redirect:/home";
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof UnknownAccountException){
                model.addAttribute("msg","没有当前用户");
            }
            if (e instanceof IncorrectCredentialsException){
                model.addAttribute("msg","密码错误");
            }
            return "login";
        }
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("home")
    public String showHome(Model model){
        marryDao.deal();
        JjclubUser user = (JjclubUser)SecurityUtils.getSubject().getPrincipal();
       // List<JjclubMenu> jjclubMenuList = jjclubUserService.getUsersMenuByLoginid(user.getLoginid());
        List<JjclubMenu> jjclubMenuList = jjclubUserService.getAllMenusByLoginid(user.getLoginid());
        model.addAttribute("menus",jjclubMenuList);
        return "index";
    }
}
